package gold.digger;

import gold.vo.TreeNode;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC114 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public void flatten(TreeNode root) {
            flattenRecur(root);
        }

        public TreeNode flattenRecur(TreeNode root) {
            if (null == root) return null;
            if (null == root.left && null == root.right) return root;

            if (null == root.left && null != root.right) return flattenRecur(root.right);
            if (null != root.left && null == root.right) {
                root.right = root.left;
                root.left = null;//clear the left;
                return flattenRecur(root.right);
            }

            // both not null
            TreeNode tempRight = root.right;
            TreeNode nextTail = flattenRecur(root.left);
            TreeNode nextNextTail = flattenRecur(root.right);

            root.right = root.left;
            root.left = null;//clear the left;
            nextTail.right = tempRight;
            return nextNextTail;
        }
    }

    public void run() {
        Solution solution = new Solution();
        TreeNode root = TreeNode.createTree("1,2,5,3,4,null,6");
        solution.flatten(root);
    }

    public static void main(String[] args) throws Exception {
        LC114 an = new LC114();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
